package dao

import (
	"a-common/constant"
	dom "a-common/domain"
	"a-system/domain/entity"
	"strings"
	"sync"
)

var (
	sysNoticeDaoTemp *SysNoticeDao
	sysNoticeDaoOnce sync.Once
)

type SysNoticeDao struct{}

func NewSysNoticeDao() *SysNoticeDao {
	sysNoticeDaoOnce.Do(func() {
		sysNoticeDaoTemp = &SysNoticeDao{}
	})
	return sysNoticeDaoTemp
}

// List 分页
func (m *SysNoticeDao) List(args *entity.SysNoticeDto) (dom.PageVo, error) {
	// 构建查询条件
	query := pgCli.Table(&entity.SysNotice{}).Where("1 = 1")
	if args.Title != "" {
		query.And("title LIKE ?", args.Title+"%")
	}
	if args.Type != "" {
		query.And("type = ?", args.Type)
	}
	if args.Status != "" {
		query.And("status = ?", args.Status)
	}
	if args.Belong != "" {
		query.And("belong = ?", args.Belong)
	}
	if args.Userid != 0 {
		query.And("userid = ?", args.Userid)
	}
	if args.Read != "" {
		query.And("read = ?", args.Userid)
	}
	if args.CreatedBy != "" {
		query.And("created_by = ?", args.CreatedBy)
	}
	if args.PageSize != 0 {
		query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize)
	}
	// 查询
	var vPage dom.PageVo
	var rows []entity.SysNoticePageVo
	total, err := query.Asc("notice_id").FindAndCount(&rows)
	if err != nil {
		return vPage, err
	}
	vPage.PageNum = args.PageNum
	vPage.PageSize = args.PageSize
	vPage.Rows = rows
	vPage.Total = total
	return vPage, err
}

// Get 查
func (m *SysNoticeDao) Get(id string) (entity.SysNoticePageVo, error) {
	var v entity.SysNoticePageVo
	_, err := pgCli.Table(&entity.SysNotice{}).ID(id).Get(&v)
	return v, err
}

// Del 删(直接删除)
func (m *SysNoticeDao) Del(ids string) (int64, error) {
	return pgCli.In("notice_id", strings.Split(ids, `,`)).Unscoped().Delete(&entity.SysNotice{})
}

// Add 增
func (m *SysNoticeDao) Add(args *entity.SysNoticeDto) (int64, error) {
	var v entity.SysNotice
	v.Title = args.Title
	v.Type = args.Type
	v.Content = args.Content
	v.Status = args.Status
	v.Belong = args.Belong
	v.Userid = args.Userid
	v.Read = args.Read
	v.CreatedBy = args.CreatedBy
	v.UpdatedBy = args.UpdatedBy
	v.Remark = args.Remark
	return pgCli.InsertOne(&v)
}

// Edit 改
func (m *SysNoticeDao) Edit(args *entity.SysNoticeDto) (int64, error) {
	var v entity.SysNotice
	v.Title = args.Title
	v.Type = args.Type
	v.Content = args.Content
	v.Status = args.Status
	v.Belong = args.Belong
	v.Userid = args.Userid
	v.Read = args.Read
	v.UpdatedBy = args.UpdatedBy
	v.Remark = args.Remark
	return pgCli.ID(args.NoticeId).Update(&v)
}

// OnRead 已读
func (m *SysNoticeDao) OnRead(id int64, updateBy string) (int64, error) {
	var v entity.SysNotice
	v.Read = constant.T
	v.UpdatedBy = updateBy
	return pgCli.ID(id).Update(&v)
}
